package icu.d4peng.cloud.common.log.utils;

import com.alibaba.fastjson.JSON;
import icu.d4peng.cloud.common.log.bean.LogBean;
import icu.d4peng.cloud.common.log.constant.LogConstant;
import icu.d4peng.cloud.common.log.context.LogContext;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.Collections;

/**
 * @author d4peng
 * @version 1.0.0
 * @date 2021-12-27 14:22
 * @description LogUtil:Log工具汇总
 */
public class LogUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogUtil.class);

    /**
     * 前预置处理:添加信息
     *
     * @param logBean 信息
     */
    public static void preHandle(LogBean logBean) {
        // 没有traceId就生成
        if (StringUtils.isEmpty(logBean.getTraceId())) {
            logBean.setTraceId(LogContext.getTraceIdGenerator().generateTraceId());
            //LOGGER.info("上一个节点未正确传递traceId,重新生成traceId:{}", logBean.getTraceId());
        }
        LogContext.setTraceId(logBean.getTraceId());

        // 如果没有spanId,会生成spanId
        LogContext.setSpanId(logBean.getSpanId());
        if (StringUtils.isEmpty(logBean.getSpanId())) {
            logBean.setSpanId(LogContext.getSpanId());
        }

        // 设置当前的ip
        logBean.setCurrentIp("127.0.0.1");
        LogContext.setCurrentIp(logBean.getCurrentIp());

        // 是否存在上游AppName
        if (StringUtils.isEmpty(logBean.getPreApp())) {
            logBean.setPreApp(LogConstant.NONE.getName());
        }
        LogContext.setPreApp(logBean.getPreApp());

        // 是否存在上游的Host
        if (StringUtils.isEmpty(logBean.getPreHost())) {
            logBean.setPreHost(LogConstant.NONE.getName());
        }
        LogContext.setPreHost(logBean.getPreHost());

        // 是否存在上游IP
        if (StringUtils.isEmpty(logBean.getPreIp())) {
            logBean.setPreIp(LogConstant.NONE.getName());
        }
        LogContext.setPreIp(logBean.getPreIp());

        // 是否存在额外数据 (这里是做扩展)
        if (ObjectUtils.isEmpty(logBean.getExtData())) {
            logBean.setExtData(Collections.emptyMap());
        }
        LogContext.setExtData(JSON.toJSONString(logBean.getExtData()));

        // 放入MDC中
        if (LogContext.isEnableMDC()) {
            String logLabel = LogContext.generateMDCLabel(logBean);
            MDC.put(LogConstant.MDC.getName(), logLabel);
        }
    }

    /**
     * 后预置处理:清除信息
     */
    public static void afterHandle() {
        LogContext.clearTraceId();
        LogContext.clearSpanId();
        LogContext.clearCurrentIp();
        LogContext.clearPreApp();
        LogContext.clearPreHost();
        LogContext.clearPreIp();
        LogContext.clearExtData();
        if (LogContext.isEnableMDC()) {
            MDC.remove(LogConstant.MDC.getName());
        }
    }
}
